import 'package:dio/dio.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_wear_app/utils/http_util.dart';
import 'package:hive/hive.dart';
// ignore: unused_import
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

// 初始化录音器
final box = Hive.box('myBox');

class AudioHandler {
  final FlutterSoundRecorder _recorder = FlutterSoundRecorder();

  // 开始录音
  Future<void> startRecording({int time = 10}) async {
    try {
      print('----------------startRecording');

      var status = await Permission.microphone.request();
      if (status != PermissionStatus.granted) {
        // 权限未授予，再次请求或提示用户
        status = await Permission.microphone.request();
        if (status != PermissionStatus.granted) {
          print('----------------权限未授予');
        }
      }
      final path = await _getRecordPath();
      print('--------------录音地址为--path: $path');
      // 打开录音器
      try {
        await _recorder.openRecorder();
      } catch (e) {
        print('录音器打开失败: $e');
      }
      try {
        await _recorder.startRecorder(
          toFile: path,
          codec: Codec.aacADTS,
          bitRate: 128000,
        );
      } catch (e) {
        print('录音启动失败: $e');
      }

      await Future.delayed(Duration(seconds: time), () async {
        print('----------------20s后开始关闭');
        final String path = await stopRecording();
        print('----------------20s后开始请求');
        if (path == '') {
          print('-------------地址为空');
          return;
        }

        final user_id = box.get("userInfo")["id"];

        print('----------------地址值 $path');
        // 创建 MultipartFile 对象
        final file = await MultipartFile.fromFile(path);

        // 上传录音文件
        var res = await HttpUtil.postFile(
          '/remote/takeSound',
          params: {"file": file, "user_id": user_id},
        );

        print('----------------20s后请求结束 $res');

        if (res['code'] == 1) {
          print(res['data']);
        } else {
          print(res['msg']);
        }
      });
    } catch (e) {
      print('录音开始失败: $e');
    }
  }

  // 停止录音
  Future<String> stopRecording() async {
    try {
      print('----------------stopRecording');
      // 停止录制
      final String? path = await _recorder.stopRecorder();
      // 关闭录音器释放资源
      await disposeRecorder();

      return path.toString();
    } catch (e) {
      print('录音停止失败: $e');
      return '';
    }
  }

  // 获取录音文件的存储路径
  Future<String> _getRecordPath() async {
    // 获取应用文档目录 getTemporaryDirectory
    final directory = await getTemporaryDirectory();
    // 生成唯一的文件名，例如使用当前时间戳 + 扩展名
    String timestampString = DateTime.now().millisecondsSinceEpoch.toString();
    print('----------------timestampString: $timestampString');
    return '${directory.path}/recording${timestampString}.aac';
  }

  // 关闭录音器释放资源
  Future<void> disposeRecorder() async {
    try {
      await _recorder.closeRecorder();
    } catch (e) {
      print('关闭录音器失败: $e');
    }
  }
}
